package com.GraduationDesign.backend.blImpl.git;

import com.GraduationDesign.backend.bl.git.GitService;
import com.GraduationDesign.backend.data.project.ProjectMapper;
import com.GraduationDesign.backend.po.DiffResponse;
import com.GraduationDesign.backend.po.GitInfo;
import com.GraduationDesign.backend.po.GitResponse;
import com.GraduationDesign.backend.po.Project;
import com.GraduationDesign.backend.utils.GitUtils;
import com.GraduationDesign.backend.utils.RequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author: wzx
 * @date: 2022/4/13
 */
@Service
public class GitServiceImpl implements GitService {
    private final static String PULL_URL="http://localhost:9000/git/pull";
    private final static String CLONE_URL="http://localhost:9000/git/clone";

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    ProjectMapper projectMapper;

    @Override
    @SneakyThrows
    public void pull(Integer programId) {
        Project project=projectMapper.getProjectInfo(programId);
        GitUtils.pull(project.getRepositoryOwner(), project.getRepositoryName());
//        gitInfo.setRepo(project.getRepositoryName());
//        gitInfo.setOwner(project.getRepositoryOwner());
//        return getGitResponse(gitInfo,PULL_URL);
    }


    @Override
    @SneakyThrows
    public void clone(GitInfo gitInfo) {
        GitUtils.clone(gitInfo.getOwner(), gitInfo.getRepo());
//        return getGitResponse(gitInfo,CLONE_URL);
    }

    private GitResponse getGitResponse(GitInfo gitInfo,String url) {
        HttpEntity<GitInfo> httpEntity=new HttpEntity<>(gitInfo);
        GitResponse gitResponse =null;
        try{
            ResponseEntity<String> responseEntity= RequestUtil.post(url, httpEntity);
            JSONObject jsonObject=JSONObject.parseObject(responseEntity.getBody());
            gitResponse = JSON.parseObject(String.valueOf(jsonObject), GitResponse.class);
        }catch (RestClientException e){
            e.printStackTrace();
        }

        return gitResponse;
    }


}
